//
//  BeautyGirlDetail.m
//  iphoneApp
//
//  Created by Liyu on 12-11-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "BeautyGirlDetail.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <QuartzCore/QuartzCore.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIAlertView+SimpleAlert.h"
#import "WaterFlowImageModel.h"
#import "ASIHTTPRequest.h"
#import "LYTabBar.h"


#define ImgUrl554 @"http://img.hb.aicdn.com/%@_fw554"
#define ContentUIScrollWidth 320.0f
#define tabBarHeight 44.0f

@interface BeautyGirlDetail ()

@end

@implementation BeautyGirlDetail
{
    CGFloat BeginScrollX;
    LYTabBar *tabBar;
    LYTabBar *navigationBar;
    CGFloat appFrameHeight;
    //ScrollView 统一高度
    CGFloat scrollViewHeight;
    
}

@synthesize imgview;
@synthesize getDataDelegate=_getDataDelegate;
@synthesize scrollView=_scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void) scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    BeginScrollX=scrollView.contentOffset.x;
}

-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat x=scrollView.contentOffset.x;
    
    if (imgview.tag==0 && x<ContentUIScrollWidth) {
        [self.scrollView setContentOffset:CGPointMake(ContentUIScrollWidth, 0) animated:NO];
    }
}

-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat x=scrollView.contentOffset.x;
    NSInteger index=  imgview.tag;
    
    NSLog(@"beginx is %f  endx is %f",BeginScrollX,x);
    
    //向左滑动时 重新加载图片
    if (x == ContentUIScrollWidth * 2) { 
        NSLog(@"left scroll");
        self.scrollView.contentOffset = CGPointMake(ContentUIScrollWidth, 0);
        WaterFlowImageModel * leftImg=[self GetImageModel:index];
        WaterFlowImageModel * middleImg=[self GetImageModel:index+1];
        WaterFlowImageModel * rightImg=[self GetImageModel:index+2];        
        [self resetLeftImg:leftImg MiddleImg:middleImg RightImg:rightImg];
        leftImgView.tag++;
        imgview.tag++;
        rightImgView.tag++;             
    }
    //向右滑动时 重新加载图片
    else if (imgview.tag!=0 && x==0.0) {
        NSLog(@"right scroll");
        self.scrollView.contentOffset = CGPointMake(ContentUIScrollWidth, 0);
        WaterFlowImageModel * leftImg=nil;
        if (imgview.tag>1) {
            leftImg=[self GetImageModel:index-2];
        }
        
        WaterFlowImageModel * middleImg=[self GetImageModel:index-1];
        WaterFlowImageModel * rightImg=[self GetImageModel:index];        
        [self resetLeftImg:leftImg MiddleImg:middleImg RightImg:rightImg];
        leftImgView.tag--;
        imgview.tag--;
        rightImgView.tag--;
    }

    [self hideOrDisplayTabBar:YES];
}

-(void) hideOrDisplayTabBar:(BOOL)isScroll
{    
    BOOL hide=![UIApplication sharedApplication].statusBarHidden;
    if (isScroll && !hide) {
        return;
    }
    
    [[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:UIStatusBarAnimationSlide];
    
    CGContextRef context=UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.3f];    

   
    navigationBar.frame=[self getTabBarHideOrDisplayRect:navigationBar ishide:hide ];
    
    tabBar.frame=[self getTabBarHideOrDisplayRect:tabBar ishide:hide ];    
    
    
    [UIView commitAnimations];
}

-(CGRect) getTabBarHideOrDisplayRect:(LYTabBar *)lyTabBar ishide:(BOOL)hide
{
    CGFloat height=lyTabBar.backgroundImageView.image.size.height;
     CGRect rect=lyTabBar.frame;
    if (hide) {
        lyTabBar.alpha=0.0f;
        rect.size.height=0.0f;
    }else {
        lyTabBar.alpha=1.0f;
        rect.size.height=height;
    }
    
    return rect;
}

//根据左 中 右的图片信息 分别重新设置  左中右的imageview与scrollview
-(void) resetLeftImg:(WaterFlowImageModel *) leftImg MiddleImg:(WaterFlowImageModel *) middleImg RightImg:(WaterFlowImageModel *) rightImg
{
    if (leftImg!=nil) {
        [leftImgView setImageWithURL:leftImg.URL]; 
        [self resetImgFrame:leftImgView AndScrollViewContentSize:leftScrollView ByWidth:leftImg.Width AndHeight:leftImg.Height];      
    }
    else {
        leftImgView.image=nil;
    }
    
        
    [imgview setImageWithURL:middleImg.URL];
    [rightImgView setImageWithURL:rightImg.URL];
    
    [self resetImgFrame:imgview AndScrollViewContentSize:middleScrollView ByWidth:middleImg.Width AndHeight:middleImg.Height];
    [self resetImgFrame:rightImgView AndScrollViewContentSize:rightScrollView ByWidth:rightImg.Width AndHeight:rightImg.Height];
}


//重新设置uiimageview的frame uiscrollview的contentsize
-(void) resetImgFrame:(UIImageView *) img AndScrollViewContentSize:(UIScrollView *)
scrollView ByWidth:(CGFloat) widht AndHeight:(CGFloat) height
{
    NSLog(@"width is %f",widht);
    CGRect rect=img.frame;
    if (widht>ContentUIScrollWidth) {
        rect=CGRectMake(0.0,0.0,ContentUIScrollWidth, ContentUIScrollWidth*height/widht);
    }
    else {
        rect=CGRectMake((ContentUIScrollWidth-widht)/2, 0, widht, height);
    }
    img.frame=rect;
    if (rect.size.height<scrollViewHeight) {
        rect.size.height=scrollViewHeight;
    }
    scrollView.contentSize=CGSizeMake(ContentUIScrollWidth, rect.size.height);
}


//根据索引从图片信息数组中获取图片相关信息Model
-(WaterFlowImageModel *) GetImageModel:(NSInteger) index
{
    NSString * url=(NSString *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"key"];
    CGFloat  width=[(NSNumber *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"width"] floatValue];
    CGFloat height=[(NSNumber *)[[[dataArr objectAtIndex:index] objectForKey:@"file"] objectForKey:@"height"] floatValue];
    
    WaterFlowImageModel * img=[[[WaterFlowImageModel alloc] init] autorelease];
    img.URL=[NSURL URLWithString:[NSString stringWithFormat:ImgUrl554,url]];
    img.Height=height;
    img.Width=width;
    
    return img;
}

-(void) initImage
{
    NSInteger index=imgview.tag;
    
    leftImgView=[[UIImageView alloc] init];
    rightImgView=[[UIImageView alloc] init];
    
    middleScrollView.contentSize=CGSizeMake(ContentUIScrollWidth, imgview.frame.size.height);
    
    [middleScrollView addSubview:imgview];    
    [leftScrollView addSubview:leftImgView];
    [rightScrollView addSubview:rightImgView];
    
    
    WaterFlowImageModel * leftImg;    
    WaterFlowImageModel * rightImg;
    WaterFlowImageModel * middleImg;
    
    middleImg=[self GetImageModel:index];
    
    if (index==0) {
        rightImg=[self GetImageModel:index+1];
        rightImgView.tag=imgview.tag+1;
    }
    else {
        leftImg=[self GetImageModel:index-1];
        rightImg=[self GetImageModel:index+1];
        leftImgView.tag=imgview.tag-1;
        rightImgView.tag=imgview.tag+1;
        
        [leftImgView setImageWithURL:leftImg.URL];
        [self resetImgFrame:leftImgView AndScrollViewContentSize:leftScrollView ByWidth:leftImg.Width AndHeight:leftImg.Height];
    }
    
    [rightImgView setImageWithURL:rightImg.URL];
    
    [self resetImgFrame:imgview AndScrollViewContentSize:middleScrollView ByWidth:middleImg.Width AndHeight:middleImg.Height];
    
    [self resetImgFrame:rightImgView AndScrollViewContentSize:rightScrollView ByWidth:rightImg.Width AndHeight:rightImg.Height];
    
    
}

-(void) savedSucces
{
    [UIAlertView DebugUIAlertView:@"saved success"];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSString * extension=[[request responseHeaders] valueForKey:@"Content-Type"];
    
    NSLog(@"houzhui---%@",extension);
    
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSLog(@"path is %@",path);
    [UIAlertView DebugUIAlertView:path  ];
    //初始化临时文件路径
    
    NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];
    
    //创建文件管理器
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断temp文件夹是否存在
    
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    
    if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
        
        [fileManager createDirectoryAtPath:folderPath 
         
               withIntermediateDirectories:YES 
         
                                attributes:nil
         
                                     error:nil];
        
    }
    
    
    //初始化临时文件路径
    NSString *savepath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"img_%d.jpg",imgview.tag]];
    
    NSString *tempPath = [path stringByAppendingPathComponent:@"temp/"];
    
    //设置文件保存路径
    
    [request setDownloadDestinationPath:savepath];
    
    //设置临时文件路径
    
    [request setTemporaryFileDownloadPath:tempPath];


    
}

-(void) downloadImageFromURL
{     
    
    
    //初始下载路径    
    NSURL *url = [self GetImageModel:imgview.tag].URL;
    
    //设置下载路径
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    
    //设置ASIHTTPRequest代理
    
    request.delegate = self;
    
       
    [request startAsynchronous];    
    

    //UIImageWriteToSavedPhotosAlbum(imgview.image, nil, nil, nil);
    
}

-(void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    [UIAlertView DebugUIAlertView:[responseHeaders objectForKey:@"Content-Type"]];
}


-(void)autoDisplayNavigationBar
{
    if (!self.navigationController.navigationBarHidden) {
        [self.navigationController setNavigationBarHidden:YES];
    }
    
}

-(void)SwitchTabBarHidden
{
    NSLog(@"lyScrollViewDidTap");
    [self hideOrDisplayTabBar:NO];   
}

-(void) tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSLog(@"tag is %d",item.tag);
    if (item.tag==1) {
        [self downloadImageFromURL];
    }
}


-(void)initTabBar
{ 
    
    CGRect  screen=[[UIScreen mainScreen] bounds];
    
    UIImage * tabBarImg=[UIImage imageNamed:@"tabbar_bottom.png"];
    
    tabBar=[[LYTabBar alloc] initWithFrame:CGRectMake(0, screen.size.height-tabBarImg.size.height, screen.size.width, tabBarImg.size.height)];
    tabBar.tag=1000;
    tabBar.backgroundImageView.image=tabBarImg;
    
    tabBar.delegate=self;

    
    UITabBarItem * item1=[[UITabBarItem alloc] initWithTitle:@"下载" image:[UIImage imageNamed:@"22-skull-n-bones.png"] tag:1];
    UITabBarItem * item2=[[UITabBarItem alloc] initWithTitle:@"收藏" image:[UIImage imageNamed:@"23-bird.png"] tag:2];
    NSMutableArray * arr=[NSMutableArray arrayWithObjects:item1,item2, nil];
    
    [item1 release];
    [item2 release];
    
    [tabBar setTabBarWithItems:arr];
    
    [self.view addSubview:tabBar];
    [tabBar release];
    
    UIImage * navigationbarimg=[UIImage imageNamed:@"tabbar_top.png"];
    
    navigationBar=[[LYTabBar alloc] initWithFrame:CGRectMake(0, 20, screen.size.width, navigationbarimg.size.height)];
    navigationBar.tag=1001;
    navigationBar.backgroundImageView.image=navigationbarimg;
    
    navigationBar.delegate=self;
    
    UITabBarItem * item3=[[UITabBarItem alloc] initWithTitle:@"下载" image:[UIImage imageNamed:@"navigationBarBackButton.png"] tag:1];
    
    NSMutableArray * arr1=[NSMutableArray arrayWithObjects:item3, nil];
    
    [item3 release];
    
    [navigationBar setTabBarWithItems:arr1];
    
    [self.view addSubview:navigationBar];
    [navigationBar release];    

}

-(void)lyTabBar:(LYTabBar *)lyTabBar didSelectItemIndex:(NSInteger)index
{
    //bottomtabbar
    if (lyTabBar.tag==1000) {
        if (index==1) {
            [self downloadImageFromURL];
        }
    }
    //navigationbar
    else if(lyTabBar.tag==1001) {
        if (index==0) {
            NSLog(@"navigationclick");
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.wantsFullScreenLayout=YES;    
        
    appFrameHeight=[[UIScreen mainScreen] applicationFrame].size.height;	
    NSLog(@"appheight is %f",appFrameHeight);
    scrollViewHeight=appFrameHeight;
    
    self.navigationItem.title=@"NewBeauty";
    [self autoDisplayNavigationBar];
    	
    [self initTabBar];            
    
    
    dataArr= [self.getDataDelegate GetImageArr];
    
    
    self.scrollView =[[LYScrollView alloc] initWithFrame:CGRectMake(0, 0, ContentUIScrollWidth, scrollViewHeight)];
    self.scrollView.contentSize=CGSizeMake(ContentUIScrollWidth*3, scrollViewHeight);
    
    self.scrollView.bounces=NO;
    self.scrollView.pagingEnabled=YES;
    self.scrollView.showsHorizontalScrollIndicator=NO; 
   
    imgview.userInteractionEnabled=NO;
    middleScrollView=[[UIScrollView alloc] init];
    leftScrollView=[[UIScrollView alloc] init];
    rightScrollView=[[UIScrollView alloc] init];
    middleScrollView.contentMode=UIViewContentModeCenter;
    leftScrollView.contentMode=UIViewContentModeCenter;
    rightScrollView.contentMode=UIViewContentModeCenter;    
    
    
    UITapGestureRecognizer * tapGesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SwitchTabBarHidden)];    
    [middleScrollView addGestureRecognizer:tapGesture];
    middleScrollView.backgroundColor=[UIColor whiteColor];
    
    [self initImage]; 
    
    CGFloat leftX=0.0;
    CGFloat middleX=ContentUIScrollWidth;    
    CGFloat rightX=ContentUIScrollWidth*2;   
    
    middleScrollView.frame=CGRectMake(middleX, 0, ContentUIScrollWidth, scrollViewHeight);
    leftScrollView.frame=CGRectMake(leftX, 0, ContentUIScrollWidth, scrollViewHeight);
    rightScrollView.frame=CGRectMake(rightX, 0, ContentUIScrollWidth, scrollViewHeight);      
    
    self.scrollView.contentOffset=CGPointMake(middleX, 0);
    [self.scrollView addSubview:middleScrollView];
    [self.scrollView addSubview:leftScrollView];
    [self.scrollView addSubview:rightScrollView];
    
    self.scrollView.delegate=self;
    
    [leftScrollView release];
    [rightScrollView release];    
    
    [self.view addSubview:self.scrollView];
    [self.view bringSubviewToFront:tabBar];
    [self.view bringSubviewToFront:navigationBar];
       
}


- (void)viewDidUnload
{
    
    dataArr=nil;
    [super viewDidUnload];    
}

-(void) dealloc
{
    dataArr=nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
